#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>

static MyFile *BuyFile(int fd,int flag)
{
	MyFile *f = (MyFile*)malloc(sizeof(MyFile));
	if(f  == NULL) return NULL;
	f->bufferlen = 0;
	f->fileno = fd;
	f->flag = flag;
	f->flush_method = LINE_FLUSH;
	memset(f->outbuffer,0,sizeof(f->bufferlen));
	return f;
}

MyFile *MyFopen(const char *path, const char *mode)
{
	int fd = -1;
	int flag = 0;
	if(strcmp(mode,"w")==0)
	{
		flag = O_CREAT | O_WRONLY | O_TRUNC;
		fd = open(path,flag,0666);
	}
	else if(strcmp(mode,"a")==0)
	{
		flag = O_CREAT | O_WRONLY | O_APPEND;
		fd = open(path,flag,0666);
	}
	else if(strcmp(mode,"r")==0)
	{
		flag = O_RDWR;
		fd = open(path,flag);
	}
	else if(strcmp(mode,"w+"))
	{
		flag = O_RDWR | O_WRONLY;
		fd = open(path,flag,0666);
	}
	else if(strcmp(mode,"a+"))
	{
		flag = O_RDWR | O_APPEND;
		fd = open(path,flag,0666);
	}
	else if(strcmp(mode,"r+"))
	{
		flag = O_RDWR | O_WRONLY;
		fd = open(path,flag);
	}
	else
	{
		//TODO
	}

	if(fd < 0) return NULL;

	MyFile *f=BuyFile(fd,flag);
	return f;
}
void MyFclose(MyFile *file)
{
	if(file->fileno < 0) return ;
	MyFFlush(file);
	close(file->fileno);
	free(file);

}
int MyFwrite(MyFile *file,void *str,int len)
{
	//1.
	memcpy(file->outbuffer+file->bufferlen,str,len);
	file->bufferlen+=len;

	//2.常识判断是否满足刷新条件，满足的话则将存在语言层缓冲区的数据通过调用系统调用将数据拷贝至内核缓冲区，从而写到磁盘、网卡或显示器。
	if((file->flush_method & LINE_FLUSH) && file->outbuffer[file->bufferlen-1] == '\n')
	{
		MyFFlush(file);
	}

	return 0;
}
void MyFFlush(MyFile *file)
{
	//ssize_t write(int fd, const void *buf, size_t count);
	//write() 函数将从缓冲区 buf 起始位置起的最多 count 个字节写入由文件描述符 fd 所引用的文件中。
	if(file->bufferlen <= 0) return;
	int n =write(file->fileno,file->outbuffer,file->bufferlen);
	file->bufferlen = 0;//从内核缓冲区刷新出去后，清空内存中的区域
	fsync(file->fileno);//直接将数据刷新到外设
	(void)n;
}
